package com.dkm.modules.wx.pile.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dkm.commons.Response;
import com.dkm.constant.Constant;
import com.dkm.dataScope.DataScope;
import com.dkm.exception.ServiceException;
import com.dkm.modules.sys.map.model.PlotPile;
import com.dkm.modules.sys.pile.model.SysPileResult;
import com.dkm.modules.sys.plot.service.PlotService;
import com.dkm.modules.wx.city.mapper.PlotMapper;
import com.dkm.modules.wx.city.model.PlotModel;
import com.dkm.modules.wx.pile.mapper.PileMapper;
import com.dkm.modules.wx.pile.model.ChargingPile;
import com.dkm.modules.wx.pile.model.PileResult;
import com.dkm.modules.wx.pile.model.PlotPileTree;
import com.dkm.modules.wx.pile.service.PileService;
import com.dkm.modules.wx.port.service.ChargingPortService;
import com.dkm.modules.wx.rule.mapper.RuleMapper;
import com.dkm.modules.wx.rule.model.Rule;
import com.dkm.util.StringUtils;
import com.dkm.util.excel.ExportExcelUtil;
import com.dkm.util.text.Convert;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName ChargingPileSericeImpl
 * @Description:
 * @Author 杨膑
 * @Date 2019/9/5
 * @Version V1.0
 **/
@Service
public class PileSericeImpl implements PileService {
    @Autowired
    private PileMapper chargingPileMapper;
    @Autowired
    private PlotMapper plotMapper;
    @Autowired
    private RuleMapper ruleMapper;
    @Autowired
    private ChargingPortService portService;
    @Autowired
    PlotService plotService;


    /**
     * @描述 获取充电桩数据
     * @参数 [page, params 查询参数]
     * @返回值 com.baomidou.mybatisplus.core.metadata.IPage<com.dkm.modules.wx.pile.model.PileResult>
     * @创建人 yangbin
     * @创建时间 2019/10/5
     */
    @Override
    @DataScope(alias = "a.userId")
    public IPage<SysPileResult> getPage(Map<String, String> params, Page<SysPileResult> page) {
        // 分页查询充电桩列表数据
        List<SysPileResult> pilePageList = chargingPileMapper.getPilePageList(page, params);
        page.setRecords(pilePageList);
        // 把查询到的数据组装成page类型
        return page;

    }


    /**
     * @描述 充电桩添加
     * @参数 [chargingPile]
     * @返回值 void
     * @创建人 yangbin
     * @创建时间 2019/10/21
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(ChargingPile chargingPile) {

        this.validateAndSetPlot(chargingPile);

        // 查询平台默认规则
        List<Rule> sysRuleList = ruleMapper.selectDefaultRuleList(chargingPile);
        /*为充电桩设置默认规则*/
        for (Rule rule : sysRuleList) {
            String ruleType = rule.getRuleType();
            if (Constant.RULE_TYPE_CARD.equals(ruleType)) {
                chargingPile.setCardRuleId(rule.getId().toString());
            }
            if (Constant.RULE_TYPE_WX.equals(ruleType)) {
                chargingPile.setWxRuleId(rule.getId().toString());
            }
        }
        chargingPile.setCreateTime(new Date());

        /*添加充电桩*/
        chargingPileMapper.insert(chargingPile);

        /*添加端口 默认20个端口*/
        portService.addPortForPile(chargingPile);
    }

    /**
     * 校验入参,并维护小区数据
     *
     * @param chargingPile
     */
    private void validateAndSetPlot(ChargingPile chargingPile) {

        if (null == chargingPile.getPlot() && StringUtils.isEmpty(chargingPile.getPlotName())) {
            throw new ServiceException("小区id或小区名不能同时为空");
        }
        if (null != chargingPile.getPlot() && StringUtils.isNotEmpty(chargingPile.getPlotName())) {
            throw new ServiceException("小区id或小区名不能同时传递");
        }
        if (StringUtils.isNotEmpty(chargingPile.getPlotName()) && null == chargingPile.getRegionCode()) {
            throw new ServiceException("区域id未传递");
        }

        // 小区信息未传递,需要先新增小区
        if (StringUtils.isNotEmpty(chargingPile.getPlotName())
                && null != chargingPile.getRegionCode()) {
            PlotModel plot = new PlotModel();
            plot.setRegionCode(chargingPile.getRegionCode());
            plot.setCreateTime(new Date());
            plot.setAddress(chargingPile.getPlotName());
            plot.setPlotName(chargingPile.getPlotName());

            plotService.addPlot(plot);

            chargingPile.setPlot(Convert.toInt(plot.getId()));
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(ChargingPile chargingPile) {

        if (StringUtils.isEmpty(chargingPile.getRunningStatus())) {
            throw new ServiceException("运行状态必填");
        }
        // 入参校验
        this.validateAndSetPlot(chargingPile);

        // 如果当前设备的 代理商发生变更时,重置规则
        this.reSetRule(chargingPile);

        chargingPileMapper.updateById(chargingPile);
    }


    private void reSetRule(ChargingPile chargingPile) {
        // 微信端不改userId
        if (StringUtils.isEmpty(chargingPile.getUserId())) {
            return;
        }

        ChargingPile oldPile = chargingPileMapper.selectById(chargingPile.getId());
        if (oldPile.getUserId().equals(chargingPile.getUserId())) {
            return;
        }
        Map<String, Object> param = new HashMap<>(1);
        param.put("user_id", chargingPile.getUserId());
        List<Rule> rules = ruleMapper.selectByMap(param);

        if (CollectionUtils.isEmpty(rules)) {
            throw new ServiceException("未查询到客户的规则");
        }

        rules = rules.stream().filter(rule -> rule.getIsGive().equals(1)).collect(Collectors.toList());

        if (CollectionUtils.isEmpty(rules)) {
            throw new ServiceException("未查询到客户的默认规则");
        }

        Map<String, List<Rule>> roleMap = rules.stream().collect(Collectors.groupingBy(Rule::getRuleType));
        List<Rule> cardRule = roleMap.get(Constant.RULE_TYPE_CARD);
        List<Rule> wxRule = roleMap.get(Constant.RULE_TYPE_WX);
        if (CollectionUtils.isEmpty(cardRule) || CollectionUtils.isEmpty(wxRule)) {
            throw new ServiceException("客户的默认卡规则,或公众号规则为空");
        }
        chargingPile.setCardRuleId(cardRule.get(0).getId().toString());
        chargingPile.setWxRuleId(wxRule.get(0).getId().toString());
    }

    @Override
    /**
     *@描述 根据小区查询充电桩
     *@参数 [plotId]
     *@返回值 java.util.List<com.dkm.modules.wx.pile.model.PileResult>
     *@创建人 yangbin
     *@创建时间 2019/10/23
     */
    public List<PileResult> getPilesByPlot(int id) {
        Map<String, String> params = new HashMap<>();
        params.put("plotId", String.valueOf(id));
        return chargingPileMapper.getPilesByPlot(params);
    }

    @Override
    public Response setPileRule(String Id, String ruleId, String cardRuleId) {
        ChargingPile chargingPile = chargingPileMapper.selectById(Id);
        if (chargingPile != null) {
            /*设置充电桩公众号规则ID*/
            chargingPile.setWxRuleId(ruleId);
            /*设置充电桩公众号规则ID*/
            chargingPile.setCardRuleId(cardRuleId);
            chargingPileMapper.updateById(chargingPile);
        }
        return Response.ok();

    }

    @Override
    /**
     *@描述 获取首页小区地图充电桩数据
     *@参数 []
     *@返回值 java.util.List<com.dkm.modules.sys.map.model.PlotPile>
     *@创建人 yangbin
     *@创建时间 2019/10/20
     */
    public List<PlotPile> getPlotPile() {
        return chargingPileMapper.getPlotPile();
    }

    @Override
    /**
     *@描述 充电桩统计
     *@参数 [params]
     *@返回值 java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     *@创建人 yangbin
     *@创建时间 2019/10/20
     */
    public List<Map<String, Object>> statisticalPile(Map<String, Object> params) {
        return chargingPileMapper.statisticalPile(params);
    }

    @Override
    /**
     *@描述 获取小区充电桩树
     *@参数 [params]
     *@返回值 java.util.List<com.dkm.modules.wx.pile.model.PlotPileTree>
     *@创建人 yangbin
     *@创建时间 2019/10/23
     */
    public List<PlotPileTree> getPileTreeList(Map<String, String> params) {
        List<PlotModel> plots = plotMapper.selectList(new QueryWrapper());
        List<PlotPileTree> plotPileTrees = new ArrayList<>();
        for (PlotModel p : plots) {
            params.put("plotId", p.getId());
            List<PileResult> pileResults = chargingPileMapper.getPileByPlotAndUserId(params);
            if (pileResults.size() > 0) {
                PlotPileTree plotPileTree = new PlotPileTree();
                plotPileTree.setPoltId(Integer.parseInt(p.getId()));
                plotPileTree.setPoltNm(p.getPlotName());
                plotPileTree.setPileResults(pileResults);
                plotPileTrees.add(plotPileTree);
            }
        }
        return plotPileTrees;
    }

    @Override
    /**
     *@描述 导出充电桩列表
     *@参数 [params, httpServletResponse]
     *@返回值 void
     *@创建人 yangbin
     *@创建时间 2019/10/24
     */
    public void ExportExcel(Map<String, String> params, HttpServletResponse res) {

        /*模板名称*/
        String templateFileName = "pileTemp.xls";
        /*生成的文件名*/
        String destFileName = "pile.xls";

        List<SysPileResult> datas = chargingPileMapper.getPilePageList(null, params);
        Map<String, Object> data = new HashMap<>();
        data.put("datas", datas);
        /*生成新文件*/
        ExportExcelUtil.exportExcel(templateFileName, destFileName, data, res);

    }

    @Override
    /**
     *@描述 通过id获取充电桩信息
     *@参数 [id 充电桩ID]
     *@返回值 com.dkm.modules.wx.pile.model.ChargingPile
     *@创建人 yangbin
     *@创建时间 2019/10/26
     */
    public ChargingPile getPile(Integer id) {
        return chargingPileMapper.selectById(id);
    }

    @Override
    public List<PileResult> getPilesByPlotAndUserId(int plotId, Integer userId) {
        Map<String, String> params = new HashMap<>(8);
        params.put("plotId", String.valueOf(plotId));
        params.put("userId", userId.toString());
        return chargingPileMapper.getPileByPlotAndUserId(params);
    }
}
